//
//  PSY.m
//  AppFinance
//
//  Created by wei on 12-7-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AFPSY.h"

@implementation AFPSY

static AFPSY *_kpiPSY = nil;

static float _kpiMaxPSY = 0;
static float _kpiMinPSY = 0;

static float _kpiLastPSY = 0;

+(AFPSY*) app{
    if (_kpiPSY == nil) {
        _kpiPSY = [[self alloc] init];
    }
    return _kpiPSY;
}

+(float) kpiMaxPSY{
    return _kpiMaxPSY;
}
+(float) kpiMinPSY{
    return _kpiMinPSY;
}

+(float) kpiLastPSY{
    return _kpiLastPSY;
}

int psy_iParam[] = {12,24};

-(void) initKlineArray:(NSArray *)_kLineArray{
    kLineArray = _kLineArray;
    
    _kpiMaxPSY = -100000000;
    _kpiMinPSY = 100000000;
    
    _psyArray = nil;
}

-(void) psyData{
    if(nil == kLineArray || [kLineArray count] <= 0){
        return;
    }
    
    int n = psy_iParam[0];
    if(n > [kLineArray count]){
        return;
    }
    
    // PSY
    _psyArray = [NSMutableArray array];
    
    NSDictionary *dict;
    float pre_close = 0;
    float close = 0;
    
    [_psyArray addObject:[NSNumber numberWithFloat:0]];
    dict = [kLineArray objectAtIndex:0];
    pre_close = [[dict objectForKey:AF_K_MARKET_CLOSE] floatValue];
    
    double sum = 0.0;
    int _kLineCount = (int)[kLineArray count];
    
    
    dict = [kLineArray objectAtIndex:0];
    pre_close = [[dict objectForKey:AF_K_MARKET_CLOSE] floatValue];
    
    for (int i = 1; i < psy_iParam[0]; i++) {
        dict = [kLineArray objectAtIndex:i];
        close = [[dict objectForKey:AF_K_MARKET_CLOSE] floatValue];
        
        if (close > pre_close) {
            sum++;
        }
        pre_close = close;
        
        [_psyArray addObject:[NSNumber numberWithFloat:0]];
    }
    
    double d_100 = 100;
    float psy = 0;
    for(int i = psy_iParam[0]; i < _kLineCount; i++){
        dict = [kLineArray objectAtIndex:i];
        close = [[dict objectForKey:AF_K_MARKET_CLOSE] floatValue];
        
        if(close > pre_close){
            sum++;
        }
        
        psy = (float)((sum / (double)psy_iParam[0]) * d_100);
        pre_close = close;
        
        [_psyArray addObject:[NSNumber numberWithFloat:psy]];
        
        int j = (i - psy_iParam[0]) + 1;
        dict = [kLineArray objectAtIndex:j];
        float close_j = [[dict objectForKey:AF_K_MARKET_CLOSE] floatValue];
        dict = [kLineArray objectAtIndex:(j-1)];
        float close_j2 = [[dict objectForKey:AF_K_MARKET_CLOSE] floatValue];
        
        if(close_j > close_j2){
            sum--;
        }
        
        if (_kpiMaxPSY < psy) {
            _kpiMaxPSY = psy;
        }
        if (_kpiMinPSY > psy) {
            _kpiMinPSY = psy;
        }
        
        if (i == (_kLineCount - 1)) {
            _kpiLastPSY = psy;
        }
    }
}

-(NSMutableArray *) kPSYArray{
    return _psyArray;
}
@end
